package cn.mdx.common.utils;

import cn.mdx.common.exceptions.CheckException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class FileUtil {

	public static int PAGESIZE=8;

	 /**
     * 获取时间戳字符串
     */
    public static String getTimer(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(date);
    }
    
    
    /**
     * 获取随机数字符串
     */
    public static String getRandom(int a){
        Random random = new Random();
        StringBuilder buffer = new StringBuilder("");
        for (int i = 0;i<a;i++){
            int b = random.nextInt(10);
            buffer.append(b).append("");
        }
        return buffer.toString();
    }

    public static String getFileFormatName(String fileName) {
        int num = fileName.lastIndexOf(".");
        if(num>0 && num!=(fileName.length()-1)) {
            return fileName.substring(fileName.lastIndexOf("."));
        }
        return null;
    }

    public static Boolean isImg(String fileName) {
        String[] imgs = {".jpg",".png",".jpeg",".gif",".bmp"};
        String fileFormat = getFileFormatName(fileName);
        if(fileFormat != null) {
            for(String str : imgs) {
                if(str.toLowerCase().equals(fileFormat.toLowerCase())) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String saveImgFile(HttpSession session, MultipartFile file, String absolutePath) throws IOException {
        if (file==null || file.getSize()==0){
            return null;
        }
        if(isImg(file.getOriginalFilename())) {
            return saveFile(session,file,absolutePath);
        } else {
            throw new CheckException("不支持该文件类型");
        }

    }


    public static String saveFile(HttpSession session, MultipartFile file, String absolutePath) throws IOException {
        if (file==null && file.getSize()==0){
            return null;
        }
        String path = session.getServletContext().getRealPath(absolutePath);
        String filename = getTimer() + getRandom(2) + getFileFormatName(file.getOriginalFilename());
        File filepath = new File(path,filename);
        // 判断路径是否存在，如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        String realPath = path + File.separator + filename;
        file.transferTo(new File(realPath));
        return absolutePath + filename;
    }


    public static String saveFiles(HttpSession session, MultipartFile[] files, String absolutePath) throws IOException {
        return saveFiles(session,files,absolutePath,files.length);
    }

    public static String saveFiles(HttpSession session, MultipartFile[] files, String absolutePath, Integer length ) throws IOException {
        if (files==null) {
            return null;
        }

        if (length==null){
            length = files.length;
        }
        length = length > files.length ? files.length : length;

        StringBuffer sb = new StringBuffer();
        String path =  session.getServletContext().getRealPath(absolutePath);
        for (int i=0; i<length; i++) {
            String filename = getTimer() + getRandom(2) + ".jpg";
            File filepath = new File(path,filename);
            // 判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            String realPath = path + File.separator + filename;
            sb.append(absolutePath + filename);
            if (i != length-1) {
                sb.append("&&");
            }
            // 将上传文件保存到一个目标文件当中
            files[i].transferTo(new File(realPath));
        }
        return sb.toString();
    }


    /**
     * 删除文件
     */
    public static void deleteFiles(HttpSession session, String[] paths){
        if(paths == null) {
            return;
        }
        for (String path : paths){
            deleteFile(session,path);
        }

    }

    public static void deleteFile(HttpSession session, String path){
        if(path == null) {
            return;
        }
        String realURL = session.getServletContext().getRealPath(path);
        File file = new File(realURL);
        if (file.exists()){
            file.delete();
        }

    }


    public static String Change(String log_time) {
        return log_time.replace('/', '-');
    }

    public static void delFolder(String folderPath) {
        try {
            File file=new File(folderPath);
            if(file.exists()) {
                delAllFile(folderPath); //删除完里面所有内容
                String filePath = folderPath;
                filePath = filePath.toString();
                File myFilePath = new File(filePath);
            }
            else{
                return ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //删除指定文件夹下的所有文件

    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public static String getDate(){
        Date date=new Date();
        SimpleDateFormat simple=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simple.format(date);
    }
}


